Springboot-Validate-全局Exception记录 - 孤风 - CSDN博客

创建时间:2019/11/14 10:20
来源:https://blog.csdn.net/weixin_43549578/article/details/90242559


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

     SpringBoot在内部通过集成hibernate-validation,可以直接使用。项目中我们需要经常的去判断前端传递到后端的数据是否正确,这个时候需要些大量的if语句,代码相对比较中。这个时候validation就发挥了很大的作用。
 

Bean Validation 中内置的 验证规则:
注解   作用
@Valid 被注释的元素是一个对象,需要检查此对象的所有字段值
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式
   
Hibernate Validator 验证规则:                              
注解 作用
@Email 被注释的元素必须是电子邮箱地址
@Length(min=, max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=, max=) 被注释的元素必须在合适的范围内
@NotBlank 被注释的字符串的必须非空
@URL(protocol=, host=,    port=,  regexp=, flags=) 被注释的字符串必须是一个有效的url
@CreditCardNumber 被注释的字符串必须通过Luhn校验算法, 银行卡,信用卡等号码一般都用Luhn 计算合法性
@ScriptAssert (lang=, script=, alias=) 要有Java Scripting API 即JSR 223 
   
   
  注意区分:
注解  作用
@NotNull   任何对象的value不能为null
@NotEmpty 集合对象的元素不为0,即集合不为空,也可以用于字符串不为null
@NotBlank 只能用于字符串不为null,并且字符串trim()以后length要大于0
  1. 1
    此处使用spring内置的Validate:
  2. 2
  3. 3
    pom:
  1. 1
    <dependency>
  2. 2
    <groupId>org.springframework.boot</groupId>
  3. 3
    <artifactId>spring-boot-starter-web</artifactId>
  4. 4
    </dependency>
其内置了:
  1. 1
    <dependency>
  2. 2
    <groupId>org.hibernate</groupId>
  3. 3
    <artifactId>hibernate-validator</artifactId>
  4. 4
    </dependency>
  5. 5
    <dependency>
  6. 6
    <groupId>com.fasterxml.jackson.core</groupId>
  7. 7
    <artifactId>jackson-databind</artifactId>
  8. 8
    </dependency>
  1. 1
    使用:
  2. 2
    1.请求方法中的请求参数上直接添加验证规则 如:@NotNull ,这里需要注意的是在该类上面需要添加@Validated。千万不要忘记,不然不会生效。
  1. 1
    /**
  2. 2
    *
  3. 3
    *@NotBlank @NotNull 如果在请求的方法上 直接使用 需要在该类上添加
  4. 4
    * @Validated 注解 否则 该验证注解不生效
  5. 5
    *
  6. 6
    * 如果在请求对象中的属性上使用校验 注解 需要在方法请求参数中 该对象之前使用 @Validated 对象 对象名
  7. 7
    *
  8. 8
    */
  9. 9
    @RestController
  10. 10
    //非对象接收的参数 在类上需要添加该注解
  11. 11
    @Validated
  12. 12
    public class UserController {
  13. 13
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
  14. 14
    @RequestMapping("/getUserInfo")
  15. 15
    public RestResultWrapper getUserInfo(@NotBlank(message = "地址不能为空!") @RequestParam(name = "address") String Address){
  16. 16
    User user=new User();
  17. 17
    user.setAddress("ssssssss");
  18. 18
    user.setAge(20);
  19. 19
    user.setBianhao(58588);
  20. 20
    user.setName("天狗食日");
  21. 21
    return new RestResultWrapper(user,0,"成功");
  22. 22
    }
  23. 23
  24. 24
    }

  1. 1
    2.嵌套使用验证规则。如在实体类中的属性上使用验证规则。并且此时需要在请求实体类旁边添加@Validated
  2. 2
  1. 1
    @Data
  2. 2
    public class UserRequest {
  3. 3
  4. 4
    @NotNull(message = "姓名不能为空")
  5. 5
    private String name;
  6. 6
  7. 7
    //{user.name.notblank} 从 ValidationMessages.properties 获取到的
  8. 8
    @NotNull(message = "{user.name.notblank}")
  9. 9
    @Range(max = 150, min = 1, message = "年龄范围应该在1-150内。")
  10. 10
    private Integer age;
  11. 11
  12. 12
    @NotNull(message = "编号不能为空")
  13. 13
    private Integer bianhao;
  14. 14
  15. 15
    @NotNull(message = "地址不能为空")
  16. 16
    private String address;
  17. 17
  18. 18
    }
  1. 1
    @RestController
  2. 2
    public class ValidateController {
  3. 3
  4. 4
  5. 5
    /**
  6. 6
    * 结果是空的
  7. 7
    * @param userRequest
  8. 8
    * @return
  9. 9
    */
  10. 10
    @RequestMapping("/getUserOne")
  11. 11
    public RestResultWrapper getUserOne(@Validated UserRequest userRequest){
  12. 12
    User user=new User();
  13. 13
    user.setAddress("ssssssss");
  14. 14
    user.setAge(20);
  15. 15
    user.setBianhao(58588);
  16. 16
    user.setName("天狗食日");
  17. 17
    return new RestResultWrapper(user,0,"成功");
  18. 18
    }
  19. 19
    }
  1. 1
           
  2. 2
    异常处理:
  3. 3
    验证不通过的时候一般使用全局异常进行处理。设计到三个类:
ConstraintViolationException(方法参数校验异常)如实体类中的@Size注解配置和数据库中该字段的长度不统一等问题
MethodArgumentNotValidException(Bean 校验异常)
BindException (参数绑定异常)

请求时候不加任何参数:BindException

 

  1. 1
    package com.springboot.validate.springbootvalidateexception.exception;
  2. 2
  3. 3
  4. 4
    import com.springboot.validate.springbootvalidateexception.constant.RestResultWrapper;
  5. 5
    import org.slf4j.Logger;
  6. 6
    import org.slf4j.LoggerFactory;
  7. 7
    import org.springframework.http.HttpStatus;
  8. 8
    import org.springframework.util.CollectionUtils;
  9. 9
    import org.springframework.validation.BindException;
  10. 10
    import org.springframework.validation.FieldError;
  11. 11
    import org.springframework.validation.ObjectError;
  12. 12
    import org.springframework.web.HttpRequestMethodNotSupportedException;
  13. 13
    import org.springframework.web.bind.MethodArgumentNotValidException;
  14. 14
    import org.springframework.web.bind.MissingServletRequestParameterException;
  15. 15
    import org.springframework.web.bind.annotation.ExceptionHandler;
  16. 16
    import org.springframework.web.bind.annotation.ResponseBody;
  17. 17
    import org.springframework.web.bind.annotation.RestControllerAdvice;
  18. 18
  19. 19
    import javax.servlet.http.HttpServletRequest;
  20. 20
    import javax.validation.ConstraintViolationException;
  21. 21
    import java.text.SimpleDateFormat;
  22. 22
    import java.util.*;
  23. 23
    import java.util.stream.Collectors;
  24. 24
  25. 25
    /**
  26. 26
    * 全局异常处理 无法处理filter抛出的异常
  27. 27
    */
  28. 28
    @RestControllerAdvice
  29. 29
    public class OnlineGlobalException {
  30. 30
  31. 31
    private static Logger logger = LoggerFactory.getLogger(OnlineGlobalException.class);
  32. 32
  33. 33
    /**
  34. 34
    * 方法参数校验异常 Validate
  35. 35
    * @param request
  36. 36
    * @param ex
  37. 37
    * @return
  38. 38
    */
  39. 39
    @ExceptionHandler(ConstraintViolationException.class)
  40. 40
    @ResponseBody
  41. 41
    public RestResultWrapper handleValidationException(HttpServletRequest request, ConstraintViolationException ex) {
  42. 42
    logger.error("异常:" + request.getRequestURI(), ex);
  43. 43
    String collect = ex.getConstraintViolations().stream().filter(Objects::nonNull)
  44. 44
    .map(cv -> cv == null ? "null" : cv.getPropertyPath() + ": " + cv.getMessage())
  45. 45
    .collect(Collectors.joining(", "));
  46. 46
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  47. 47
    logger.info("请求参数异常",collect);
  48. 48
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  49. 49
    restResultWrapper.setMessage(ex.getMessage());
  50. 50
    return restResultWrapper;
  51. 51
    }
  52. 52
  53. 53
    /**
  54. 54
    * Bean 校验异常 Validate
  55. 55
    * @param request
  56. 56
    * @param exception
  57. 57
    * @return
  58. 58
    */
  59. 59
    @ExceptionHandler(value = MethodArgumentNotValidException.class) //400
  60. 60
    @ResponseBody
  61. 61
    public RestResultWrapper methodArgumentValidationHandler(HttpServletRequest request, MethodArgumentNotValidException exception){
  62. 62
    logger.info("异常:" + request.getRequestURI(), exception);
  63. 63
    logger.info("请求参数错误!{}",getExceptionDetail(exception),"参数数据:"+showParams(request));
  64. 64
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  65. 65
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  66. 66
    if (exception.getBindingResult() != null && !CollectionUtils.isEmpty(exception.getBindingResult().getAllErrors())) {
  67. 67
    restResultWrapper.setMessage(exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
  68. 68
    } else {
  69. 69
    restResultWrapper.setMessage(exception.getMessage());
  70. 70
    }
  71. 71
    return restResultWrapper;
  72. 72
    }
  73. 73
  74. 74
    /**
  75. 75
    * 绑定异常
  76. 76
    * @param request
  77. 77
    * @param pe
  78. 78
    * @return
  79. 79
    */
  80. 80
    @ExceptionHandler(BindException.class)
  81. 81
    @ResponseBody
  82. 82
    public RestResultWrapper bindException(HttpServletRequest request, BindException pe) {
  83. 83
    logger.error("异常:" + request.getRequestURI(), pe);
  84. 84
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  85. 85
    Map map=new HashMap();
  86. 86
    if(pe.getBindingResult()!=null){
  87. 87
    List<ObjectError> allErrors = pe.getBindingResult().getAllErrors();
  88. 88
    allErrors.stream().filter(Objects::nonNull).forEach(objectError -> {
  89. 89
    map.put("请求路径:"+request.getRequestURI()+"--请求参数:"+(((FieldError) ((FieldError) allErrors.get(0))).getField().toString()),objectError.getDefaultMessage());
  90. 90
    });
  91. 91
    }
  92. 92
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  93. 93
    restResultWrapper.setMessage("请求参数绑定失败");
  94. 94
    restResultWrapper.setResult(map.toString());
  95. 95
    return restResultWrapper;
  96. 96
    }
  97. 97
  98. 98
  99. 99
    /**
  100. 100
    * 访问接口参数不全
  101. 101
    * @param request
  102. 102
    * @param pe
  103. 103
    * @return
  104. 104
    */
  105. 105
    @ExceptionHandler(MissingServletRequestParameterException.class)
  106. 106
    @ResponseBody
  107. 107
    public RestResultWrapper missingServletRequestParameterException(HttpServletRequest request, MissingServletRequestParameterException pe) {
  108. 108
    logger.error("异常:" + request.getRequestURI(), pe);
  109. 109
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  110. 110
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  111. 111
    restResultWrapper.setMessage("该请求路径:"+request.getRequestURI()+"下的请求参数不全:"+pe.getMessage());
  112. 112
    return restResultWrapper;
  113. 113
    }
  114. 114
  115. 115
    /**
  116. 116
    * HttpRequestMethodNotSupportedException
  117. 117
    * @param request
  118. 118
    * @param pe
  119. 119
    * @return
  120. 120
    */
  121. 121
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  122. 122
    @ResponseBody
  123. 123
    public RestResultWrapper httpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException pe) {
  124. 124
    logger.error("异常:" + request.getRequestURI(), pe);
  125. 125
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  126. 126
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  127. 127
    restResultWrapper.setMessage("请求方式不正确");
  128. 128
    return restResultWrapper;
  129. 129
    }
  130. 130
  131. 131
  132. 132
    /**
  133. 133
    * 其他异常
  134. 134
    * @param request
  135. 135
    * @param pe
  136. 136
    * @return
  137. 137
    */
  138. 138
    @ExceptionHandler(Exception.class)
  139. 139
    @ResponseBody
  140. 140
    public RestResultWrapper otherException(HttpServletRequest request, Exception pe) {
  141. 141
    logger.error("异常:" + request.getRequestURI(), pe);
  142. 142
    RestResultWrapper<String> restResultWrapper = new RestResultWrapper();
  143. 143
    restResultWrapper.setCode(HttpStatus.BAD_REQUEST.value());
  144. 144
    restResultWrapper.setMessage(getExceptionDetail(pe));
  145. 145
    return restResultWrapper;
  146. 146
    }
  147. 147
  148. 148
    /**
  149. 149
    * 异常详情
  150. 150
    * @param e
  151. 151
    * @return
  152. 152
    */
  153. 153
    private String getExceptionDetail(Exception e) {
  154. 154
    StringBuilder stringBuffer = new StringBuilder(e.toString() + "\n");
  155. 155
    StackTraceElement[] messages = e.getStackTrace();
  156. 156
    Arrays.stream(messages).filter(Objects::nonNull).forEach(stackTraceElement -> {
  157. 157
    stringBuffer.append(stackTraceElement.toString() + "\n");
  158. 158
    });
  159. 159
    return stringBuffer.toString();
  160. 160
    }
  161. 161
  162. 162
    /**
  163. 163
    * 请求参数
  164. 164
    * @param request
  165. 165
    * @return
  166. 166
    */
  167. 167
    public String showParams(HttpServletRequest request) {
  168. 168
    Map<String,Object> map = new HashMap<String,Object>();
  169. 169
    StringBuilder stringBuilder=new StringBuilder();
  170. 170
    Enumeration paramNames = request.getParameterNames();
  171. 171
    stringBuilder.append("----------------参数开始-------------------");
  172. 172
    stringBuilder.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  173. 173
    if(Objects.nonNull(paramNames)){
  174. 174
    while (paramNames.hasMoreElements()) {
  175. 175
    String paramName = (String) paramNames.nextElement();
  176. 176
    String[] paramValues = request.getParameterValues(paramName);
  177. 177
    if (paramValues.length >0) {
  178. 178
    String paramValue = paramValues[0];
  179. 179
    if (paramValue.length() != 0) {
  180. 180
    stringBuilder.append("参数名:").append(paramName).append("参数值:").append(paramValue);
  181. 181
    }
  182. 182
    }
  183. 183
    }
  184. 184
    }
  185. 185
    stringBuilder.append("----------------参数结束-------------------");
  186. 186
    return stringBuilder.toString();
  187. 187
    }
  188. 188
  189. 189
  190. 190
    }

  验证请求参数还可以通过自定义注解:

如:

手机号码:

  1. 1
    @ConstraintComposition(CompositionType.OR)
  2. 2
    //模式
  3. 3
    @Pattern(regexp = "1[3|4|5|7|8|6][0-9]\\d{8}")
  4. 4
    @Null
  5. 5
    @Length(min = 0, max = 16)
  6. 6
    @Documented
  7. 7
    @Constraint(validatedBy = {})
  8. 8
    @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER })
  9. 9
    @Retention(RUNTIME)
  10. 10
    @ReportAsSingleViolation
  11. 11
    public @interface PhoneVerification {
  12. 12
    String message() default "手机号校验错误";
  13. 13
  14. 14
    //分组
  15. 15
    Class<?>[] groups() default {};
  16. 16
  17. 17
    //负载
  18. 18
    Class<? extends Payload>[] payload() default {};
  19. 19
    }

身份证:

  1. 1
    @Target( { METHOD, FIELD, ANNOTATION_TYPE })
  2. 2
    @Retention(RetentionPolicy.RUNTIME)
  3. 3
    @Constraint(validatedBy = CardValidate.Validator.class)
  4. 4
    @Documented
  5. 5
    public @interface CardValidate {
  6. 6
    String message() default "invalid phone number";
  7. 7
  8. 8
    //分组
  9. 9
    Class<?>[] groups() default {};
  10. 10
  11. 11
    //负载
  12. 12
    Class<? extends Payload>[] payload() default {};
  13. 13
  14. 14
    class Validator implements ConstraintValidator<CardValidate, String> {
  15. 15
    @Override
  16. 16
    public boolean isValid(String carid, ConstraintValidatorContext arg1){
  17. 17
    if(!StringUtils.isEmpty(carid)){
  18. 18
    //RegexValidateUtils.checkCard(carid)
  19. 19
    //TODO 验证逻辑
  20. 20
    return true;
  21. 21
    }else{
  22. 22
    return true;
  23. 23
    }
  24. 24
    }
  25. 25
    }
  26. 26
    }

分组校验:https://www.cnkirito.moe/spring-validation/

@Validated和@Valid区别:https://blog.csdn.net/qq_27680317/article/details/79970590

@Validated和@Valid在嵌套验证功能上的区别:

          @Validated:用在方法入参上无法单独提供嵌套验证功能。不能用在成员属性(字段)上,也无法提示框架进行嵌套验证。能配合嵌套验证注解@Valid进行嵌套验证。

         @Valid:用在方法入参上无法单独提供嵌套验证功能。能够用在成员属性(字段)上,提示验证框架进行嵌套验证。能配合嵌套验证注解@Valid进行嵌套验证。

代码参考:https://github.com/timeday/springboot-validateexception

文章最后发布于: 2019-05-17 23:50:05